import axios from 'axios'
import { Message } from 'element-ui'
import { getTimeStamp, setTimeStamp } from '@/utils/auth.js'
import store from '@/store'
// import { getTimeStamp } from '@/utils/auth'
// const TimeOut = 3600 // 定义超时时间
// create an axios instance
function isTimeut() {
  const duration = 600000000
  return Date.now() - getTimeStamp() > duration
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(config => {
  // 如果有token，给后面的请求加上token
  if (store.getters.token) {
    // 主动介入
    config.headers.Authorization = `Bearer ${store.getters.token}`
    if (isTimeut()) {
      store.dispatch('user/logout')
      return Promise.reject(new Error('token过期'))
    }
    setTimeStamp()
  }
  return config
})

// 响应拦截器
// 响应拦截器中可以接受两个参数，都是回调函数
service.interceptors.response.use(
  res => {
    const { success, message, data } = res.data
    if (success) {
      // 数据成功
      // console.log(res)
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  }, err => {
    console.dir(err)
    if (err.response.data.code === 10002) {
      store.dispatch('user/logout')
    }

    Message.error(err.message)
    return Promise.reject(err)
  }
)

export default service
